<!DOCTYPE html>
<html>
<head>
<script src="/js-test-resources/js-test.js"></script>
</head>
<body>
<div id="description"></div>
<div id="console"></div>
<script type="text/javascript">
description("WebSocket should fail the connection if it has failed to read a Blob.");

window.jsTestIsAsync = true;

function startsWith(target, prefix)
{
    return target.indexOf(prefix) === 0;
}

var fileSystemSize = 1024;
var fileName = "websocket-send-file-blob-fail.txt";
var messageToWrite = "This message shouldn't be sent.";

function runTest()
{
    if (!window.webkitRequestFileSystem) {
        testFailed("window.webkitRequestFileSystem is not available.");
        finishJSTest();
        return;
    }

    webkitRequestFileSystem(TEMPORARY, fileSystemSize, didGetFileSystem, didFail);
}

function didGetFileSystem(fileSystem)
{
    debug("Got FileSystem object.");
    fileSystem.root.getFile(fileName, {create: true}, didCreateFile, didFail);
}

var fileEntry;

function didCreateFile(entry)
{
    debug("File created.");
    fileEntry = entry;
    shouldBeTrue("fileEntry.isFile");
    fileEntry.createWriter(didGetFileWriter, didFail);
}

function didGetFileWriter(writer)
{
    writer.truncate(0);
    writer.onerror = function()
    {
        testFailed("FileWriter operation failed.");
        endTest();
    };
    writer.onwrite = function()
    {
        writer.write(new Blob([messageToWrite]));
        writer.onwrite = didWriteFile;
    };
}

function didWriteFile()
{
    debug("Wrote to file.");
    fileEntry.file(didGetFile, didFail);
}

var fileObject;

function didGetFile(file)
{
    debug("Got File object.");
    fileObject = file;

    // Delete the file object before it is read. This should cause the subsequent read operation
    // to fail reliably.
    fileEntry.remove(didRemoveFile, didFail);
}

function didRemoveFile()
{
    debug("File deleted.");
    fileEntry = null; // To prevent the file from getting deleted again.
    var ws = new WebSocket("ws://127.0.0.1:8880/echo");
    ws.onopen = function()
    {
        ws.send(fileObject); // This operation should fail and the connection should be aborted.
    };
    ws.onclose = function(event)
    {
        closeEvent = event;
        shouldBeFalse("closeEvent.wasClean");
        endTest();
    };
}

function didFail(fileError)
{
    testFailed("FileSystem API operation failed: error code = " + fileError.code);
    endTest();
}

function endTest()
{
    if (fileEntry) {
        debug("Deleting the file.");
        fileEntry.remove(finishJSTest, finishJSTest);
    } else
        finishJSTest();
}

runTest();

</script>
</body>
</html>
